import tensorflow as tf

W = tf.Variable([.3], dtype=tf.float32, name='W')  # W为要获取的值，初始默认为0.3(初始值为人为设定，较准确的初始值可以减少训练步数)
b = tf.Variable([-.3], dtype=tf.float32, name="b")  # b为要获取的值，初始默认为0.3(初始值为人为设定，较准确的初始值可以减少训练步数)
x = tf.placeholder(tf.float32, name='x')  # x为输入值，通过传递多个值来进行训练

linear_model = W * x + b  # linear_model定义计算逻辑

y = tf.placeholder(tf.float32)  # yy模拟提供的目标值
# 定义损失函数为各值相差的平方和
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
tf.summary.scalar('loss', loss)  # 添加loss值监听

# 使用步进为0.01的梯度下降算法来最小化损失函数
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# 创建会话
sess = tf.InteractiveSession()

log_writer = tf.summary.FileWriter('data_log/l019', sess.graph)

# 初始化
init_op = tf.global_variables_initializer()
sess.run(init_op)

x_train = [1,  2,  3,  4]  # 输入值
y_train = [0, -1, -2, -3]  # 输出值
# 训练1000次梯度下降算法,来改变W、b值，使损失函数最小化
for i in range(1000):
    sess.run(train, {x: x_train, y: y_train})
# 最后一次，获取值
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss))
sess.close()
log_writer.close()
